<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
    <meta name="_csrf" th:if="${_csrf}" th:content="${_csrf.token}"/>
    <meta name="_csrf_header" th:if="${_csrf}" th:content="${_csrf.headerName}"/>
    <title>Service UI Fragment</title>
    <link href="../../static/css/cas.css" rel="stylesheet" th:remove="tag"/>
</head>

<body>
<main class="container mt-3 mb-3">
    <div th:fragment="webAuthnLogin">

        <script type="text/javascript" th:src="@{#{webjars.text-encoding.js}}"></script>
        <script type="text/javascript" th:src="@{#{webjars.text-encoding-indexes.js}}"></script>
        <script type="text/javascript" th:src="@{#{webjars.whatwg-fetch.js}}"></script>
        <script type="text/javascript" th:src="@{#{webjars.base64.js}}"></script>

        <script type="text/javascript" th:src="@{#{webjars.sweet-alert.js}}"></script>
        <script type="text/javascript" th:src="@{#{webjars.highlight.js}}"></script>
        <link rel="stylesheet" type="text/css" th:href="@{#{webjars.sweet-alert.css}}" />
        <link rel="stylesheet" type="text/css" th:href="@{#{webjars.animate.css}}" />
        <link rel="stylesheet" type="text/css" th:href="@{#{webjars.highlight.css}}"/>
        
        <script type="text/javascript" th:inline="javascript">
            /*<![CDATA[*/
            const appId = /*[[${webauthnApplicationId}]]*/;
            /*]]>*/
        </script>

        <script type="text/javascript" th:inline="javascript">
            const authFailTitle = [[#{ screen.authentication.webauthn.authn.fail.title }]];
            const authFailDesc = [[#{ screen.authentication.webauthn.authn.fail.desc }]];
        </script>

        <script th:src="@{/js/webauthn/webauthn.js}"></script>

        <div style="display: none" id="diagnostics">
            <p>
                <button class="btn btn-primary" type="button" data-toggle="collapse"
                        data-target="#serverResponse" aria-expanded="false" aria-controls="serverResponse">
                    Server Response
                </button>
                <button class="btn btn-primary" type="button" data-toggle="collapse"
                        data-target="#authenticatorResponse" aria-expanded="false" aria-controls="authenticatorResponse">
                    Authenticator Response
                </button>
                <button class="btn btn-primary" type="button" data-toggle="collapse"
                        data-target="#requestPanel" aria-expanded="false" aria-controls="requestPanel">
                    Request
                </button>
            </p>
            <div class="collapse" id="serverResponse">
                <div class="card card-body">
                    <h4>Server Response:</h4>
                    <pre id="session"></pre>
                    <pre id="server-response"></pre>
                </div>
            </div>
            <div class="collapse" id="authenticatorResponse">
                <div class="card card-body">
                    <h4>Authenticator Response:</h4>
                    <pre id="authenticator-response"></pre>
                </div>
            </div>
            <div class="collapse" id="requestPanel">
                <div class="card card-body">
                    <h4>WebAuthN Request:</h4>
                    <pre id="request"></pre>
                </div>
            </div>
        </div>

        <div id="webauthnContainer" class="d-flex justify-content-center flex-column mdc-card card p-4 m-auto">
            <div class="d-flex justify-content-center flex-column align-items-center">
                <h2 id="status" th:text="#{screen.authentication.webauthn.login.title}" />
            </div>
            <p id="description" th:text="#{screen.authentication.webauthn.login.desc}">Login</p>

            <div id="errorPanel" class="banner banner-danger alert alert-danger alert-dismissible mb-4"
                 th:if="${flowRequestContext != null && flowRequestContext.messageContext.hasErrorMessages()}">
                <p th:each="message : ${flowRequestContext.messageContext.allMessages}"
                   th:utext="#{${message.text}}">
                    Error Message Text
                </p>
            </div>

            <div id="messages"></div>
            <div id="device-info">
                <div class="d-flex justify-content-center flex-column align-items-center">
                    <br>
                    <img id="device-icon" alt="Device icon"/>
                    <br>
                    <span id="device-name"></span>
                </div>
            </div>
            <div id="loginPanel" class="d-flex justify-content-center flex-column align-items-center">
                <button class="mdc-button mdc-button--raised btn btn-primary me-2"
                        name="authnButton" id="authnButton" accesskey="a" type="button">
                    <i class="mdi mdi-fingerprint fas fa-fingerprint" aria-hidden="true"></i>
                    <span id="authnButtonText" class="mdc-button__label"
                          th:text="#{screen.welcome.button.login}">Login</span>
                </button>
            </div>

            <div id="QRCodeSection" class="row mt-2" th:if="${QRCode}">
                <p th:utext="#{screen.authentication.webauthn.qr.info}">Scan the QR code with your mobile device to authenticate.</p>

                <div class="mt-2 text-center">
                    <img alt="QR Code" id="imageQRCode" th:src="@{'data:image/jpeg;base64,' + ${QRCode}}">
                    <br>

                    <form id="webauthnQRCodeForm" th:action="${QRCodeUri + '/' + QRCodeTicket.id}" method="GET" target="_blank">
                        <div th:replace="~{fragments/submitbutton :: submitButton (
                            messageKey='screen.welcome.button.continue',
                            iconClass='mdi-qrcode fa-qrcode',
                            id='qrCodeButton', name='qrCodeButton')}"/>
                    </form>

                    <div id="QRCodeLinkContainer">
                        <pre>
                            <code th:text="${QRCodeUri + '/' + QRCodeTicket.id}"
                                  id="QRCodeLink" class="border-rounded language-html" />
                        </pre>
                    </div>

                    <script type="text/javascript" th:inline="javascript">
                        const endpointUrl = /*[[${QRCodeUri + '/' + QRCodeTicket.id + '/status'}]]*/;
                        const interval = 3000;
                        function verifyAuthenticationStatus() {
                            console.log(`Checking operation status at ${endpointUrl}`);
                            $.ajax({
                                url: endpointUrl,
                                method: 'GET',
                                success: (response, status, xhr) => {
                                    console.log(`Operation status: ${xhr.status}`);
                                    if (xhr.status === 200) {
                                        $('#token').val(response.sessionToken);
                                        const form = $('#webauthnLoginForm');
                                        console.log(`Submitting authentication form ${form.serialize()}`);
                                        clearMessages();
                                        hideDeviceInfo();
                                        Swal.close();
                                        form.submit();
                                    } else {
                                        setTimeout(verifyAuthenticationStatus, interval);
                                    }
                                },
                                error: xhr => {
                                    const errorResponse = JSON.parse(xhr.responseText);
                                    console.error(`Error: ${xhr.status} ${errorResponse.message}`);
                                    setTimeout(verifyAuthenticationStatus, interval);
                                }
                            });
                        }

                        verifyAuthenticationStatus();
                    </script>
                </div>

                <script type="text/javascript">
                    $("form#webauthnQRCodeForm").submit(() => {
                        resetDisplays();
                        $("#QRCodeSection").hide();
                        $("#authnButton").hide();
                        $("#diagnostics").hide();
                        $("#status").hide();
                        $("#description").hide();
                        $("#webauthnContainer").hide();
                        $("main#main-content").hide();

                        Swal.fire({
                            icon: "info",
                            title: "Please Wait...",
                            text: "Your authentication attempt is in progress. Do not close this window!",
                            allowOutsideClick: false,
                            showConfirmButton: false,
                            didOpen: () => Swal.showLoading()
                        });
                        return true;
                    });
                    
                    if (!isBrowserSupported()) {
                        setStatus(authFailTitle);
                        addMessage('Web Authentication (WebAuthn) is not supported by this browser.');
                        $("#messages").addClass("banner banner-danger alert alert-danger");
                        hideDeviceInfo();
                        $("#description").empty();
                        $('#webauthnLoginForm').empty();
                        $('#QRCodeSection').empty();
                        $('#loginPanel').empty();
                    }
                </script>
        </div>
        <div>
            <div class="w-100 mdc-data-table table-responsive mx-auto my-4" id="divDeviceInfo" style="display: none">
                <table id="deviceTable" class="table table-striped auto-init" style="white-space: unset">
                    <thead>
                    <tr class="mdc-data-table__header-row">
                        <th class="w-50 mdc-data-table__header-cell" role="columnheader" scope="col">Attribute</th>
                        <th class="w-50 mdc-data-table__header-cell" role="columnheader" scope="col">Value(s)</th>
                    </tr>
                    </thead>
                    <tbody class="mdc-data-table__content">
                    </tbody>
                </table>
            </div>
        </div>

        <form th:if="${QRCodeAuthentication}" method="POST" id="webauthnQRCodeVerifyForm" class="fm-v clearfix" th:action="@{/webauthn/qrverify}">
            <input type="hidden" id="token" name="token"/>
            <input type="hidden" id="principal" name="principal" th:value="${principal.id}"/>
            <input type="hidden" id="ticket" name="ticket" th:value="${QRCodeTicket.id}"/>
        </form>

        <form method="POST" id="webauthnLoginForm" class="fm-v clearfix" th:action="@{/login}">
            <input type="hidden" name="_eventId" value="validate"/>
            <input type="hidden" id="token" name="token"/>
            <input type="hidden" name="geolocation"/>
            <input type="hidden" id="authnCsrfToken" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
            <input type="hidden" name="execution" th:value="${flowExecutionKey}"/>
        </form>

        <script type="text/javascript" th:inline="javascript">
            const csrfToken = getCookie('XSRF-TOKEN');

            /*<![CDATA[*/
            let QRCodeAuthentication = /*[[${QRCodeAuthentication}]]*/;
            const QRCodeTicket = /*[[${QRCodeTicket?.id}]]*/;
            const csrfParameterName = /*[[${_csrf.parameterName}]]*/;
            /*]]>*/
            if (QRCodeTicket !== undefined && QRCodeTicket !== null) {
                $(`#webauthnQRCodeVerifyForm input[name=${csrfParameterName}]`).val(csrfToken);
            }
            if (QRCodeAuthentication === undefined || QRCodeAuthentication === null) {
                QRCodeAuthentication = false;
            }
            console.log(`Using CSRF token: ${csrfToken}`);
            console.log(`QR Code Authentication: ${QRCodeAuthentication}`);
            const url = window.location.href;
            const btn = document.getElementById('authnButton');
            btn.addEventListener('click', event => {
                $("#errorPanel").hide();
                let username = /*[[${principal?.id}]]*/;
                if (username === '' || username === null) {
                   username = $("#fm1 #username").val();
                }
                console.log(`Authenticating user: ${username}`);
                authenticate(username);
            }, false);
        </script>
        
    </div>
</main>
</body>

</html>
